package com.lagou.user.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    public static void main(String[] args) {
        Map<String, Object> payload = new HashMap<>();
        payload.put("email", "280910313@qq.com");
        payload.put("password", "123456");
        String token = createToken("280910313@qq.com123456");
        System.out.println(token);
        verifyToken(token, "280910313@qq.com123456");
    }

    public static String createToken(String content) {
        String token = null;
        try {
            Algorithm algorithm = Algorithm.HMAC256("secret");
            token = JWT.create()
                    //.withPayload(payload)
                    .withClaim("content", content)
                    .sign(algorithm);
        } catch (JWTCreationException exception){
            //Invalid Signing configuration / Couldn't convert Claims.
        }
        return token;
    }

    public static boolean verifyToken(String token, String content) {
        try {
            Algorithm algorithm = Algorithm.HMAC256("secret");
            JWTVerifier verifier = JWT.require(algorithm)
                    //.withIssuer("auth0")
                    .withClaim("content", content)
                    .build(); //Reusable verifier instance
            DecodedJWT jwt = verifier.verify(token);
            return token.equals(jwt.getToken());
        } catch (JWTVerificationException exception){
            //Invalid signature/claims
            return false;
        }
    }
}
